﻿using Daemon.Infrustructure.EF;
using Daemon.Model;
using Daemon.Repository.Contract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Daemon.Repository.EF
{
	public class ApplicationRepository : Repository<Application>, IApplicationRepository
	{
		protected override Expression<Func<Application, int>> PrimaryKeyExpression => r => r.Id;

		public ApplicationRepository(ApiDBContent context) : base(context)
		{
		}

		public string GetApplicationName(string prefix)
		{
			return GetDbQuery().FirstOrDefault(r => r.Prefix == prefix)?.Name;
		}

		public Application GetApplication(string prefix)
		{
			return GetDbQuery().FirstOrDefault(r => r.Prefix == prefix);
		}

		public Application GetApplicationByProductNames(List<string> productNames)
		{
			return (from app in GetDbQuery()
					join roleApp in Context.RoleApplication on app.Id equals roleApp.ApplicationId
					select new Application()
					{
						Id = app.Id,
						Name = app.Name,
						Prefix = app.Prefix,
						RoleApplications = roleApp
					}).FirstOrDefault(r => productNames.Contains(r.Name.Replace(" ", string.Empty)));
		}
	}
}
